<template>
  <div class="profile-outer">
    <div class="profile-card">
      <!-- 头像区域 -->
      <div class="avatar-section">
        <img 
          class="avatar" 
          :src="currentAvatarUrl" 
          @error="handleImageError"
          @click="handleAvatarChange"
        />
        <div class="avatar-hint">点击更换头像</div>
      </div>
      <!-- 用户信息区域 -->
      <div class="info-section">
        <div class="info-item">
          <span class="info-label">用户名</span>
          <span class="info-value">{{ userInfo.userName || '未设置' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">手机号</span>
          <span class="info-value">{{ userInfo.phoneNumber || '未绑定' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">电子邮箱</span>
          <span class="info-value">{{ userInfo.email || '未设置' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">密码</span>
          <span class="info-value">******</span>
        </div>
      </div>
      <div class="profile-btns">
        <button class="edit-all-btn" @click="openEditAll">修改信息</button>
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </div>
    <!-- 编辑信息弹窗（含密码） -->
    <div class="popup-mask" v-if="showEditPopup" @click="onMaskClick"></div>
    <div class="popup-container" v-if="showEditPopup">
      <div class="popup-title">修改个人信息</div>
      <input type="text" v-model="editUserName" placeholder="请输入用户名" class="popup-input" />
      <p v-if="editErrors.userName" class="error-message">{{ editErrors.userName }}</p>
      <input type="tel" v-model="editPhoneNumber" placeholder="请输入手机号" class="popup-input" />
      <p v-if="editErrors.phoneNumber" class="error-message">{{ editErrors.phoneNumber }}</p>
      <input type="email" v-model="editEmail" placeholder="请输入电子邮箱" class="popup-input" />
      <p v-if="editErrors.email" class="error-message">{{ editErrors.email }}</p>
      <div class="password-toggle" @click="showPasswordFields = !showPasswordFields">
        <span>修改密码</span>
        <span :class="['arrow', showPasswordFields ? 'up' : 'down']"></span>
      </div>
      <div v-if="showPasswordFields">
        <input type="password" v-model="oldPassword" placeholder="请输入原密码" class="popup-input" />
        <p v-if="passwordErrors.oldPassword" class="error-message">{{ passwordErrors.oldPassword }}</p>
        <input type="password" v-model="newPassword" placeholder="请输入新密码（6-20位，包含字母和数字）" class="popup-input" />
        <p v-if="passwordErrors.newPassword" class="error-message">{{ passwordErrors.newPassword }}</p>
        <input type="password" v-model="confirmPassword" placeholder="请确认新密码" class="popup-input" />
        <p v-if="passwordErrors.confirmPassword" class="error-message">{{ passwordErrors.confirmPassword }}</p>
      </div>
      <div class="popup-buttons">
        <button class="popup-btn cancel-btn" @click="cancelEdit">取消</button>
        <button class="popup-btn confirm-btn" @click="saveAllEditWithPassword">确定</button>
      </div>
    </div>
  </div>
</template>

<script>
import { API_BASE_URL } from '@/utils/api-base.js'
export default {
  data() {
    return {
      defaultAvatar: 'https://picsum.photos/200/200?random=1',
      userInfo: {
        avatarUrl: '',
        userName: '',
        phoneNumber: '',
        email: '',
        id: ''
      },
      showEditPopup: false,
      editUserName: '',
      editPhoneNumber: '',
      editEmail: '',
      editErrors: {
        userName: '',
        phoneNumber: '',
        email: ''
      },
      showPasswordFields: false,
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
      passwordErrors: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    }
  },
  computed: {
    // 计算当前应该显示的头像地址
    currentAvatarUrl() {
      return this.userInfo.avatarUrl || this.defaultAvatar;
    }
  },
  onLoad() {
    this.loadUserInfo();
  },
  methods: {
    // 加载用户信息
    loadUserInfo() {
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo) {
        this.userInfo = userInfo;
      } else {
        // 如果没有用户信息，跳转到登录页
        uni.reLaunch({
          url: '/pages/login/login'
        });
      }
    },
    
    // 处理头像加载失败
    handleImageError() {
      this.userInfo.avatarUrl = this.defaultAvatar;
    },
    
    // 更换头像
    handleAvatarChange() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.uploadAvatar(tempFilePath);
        },
        fail: (err) => {
          console.error('选择图片失败', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 上传头像到服务器
    uploadAvatar(tempFilePath) {
      const token = uni.getStorageSync('token');
      uni.showLoading({
        title: '上传中...'
      });

      uni.uploadFile({
        url: API_BASE_URL + '/api/upload/avatar',
        filePath: tempFilePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${token}`
        },
        formData: {
          'userId': this.userInfo.id
        },
        success: (uploadFileRes) => {
          uni.hideLoading();
          
          if (uploadFileRes.statusCode < 200 || uploadFileRes.statusCode >= 300) {
            console.error('上传失败，状态码:', uploadFileRes.statusCode);
            uni.showToast({
              title: `上传失败 (${uploadFileRes.statusCode})`,
              icon: 'none'
            });
            return;
          }
          
          try {
            const result = JSON.parse(uploadFileRes.data);
            if (result.success && result.url) {
              // 更新本地用户信息
              this.userInfo.avatarUrl = result.url;
              uni.setStorageSync('userInfo', this.userInfo);
              uni.showToast({
                title: '头像更新成功',
                icon: 'success'
              });
            } else {
              throw new Error(result.message || '上传失败');
            }
          } catch (e) {
            console.error('解析上传结果失败', e);
            uni.showToast({
              title: '上传失败: ' + (e.message || '未知错误'),
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          console.error('上传请求失败', err);
          uni.showToast({
            title: '网络错误，上传失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 打开整体编辑弹窗
    openEditAll() {
      this.showEditPopup = true;
      this.editUserName = this.userInfo.userName || '';
      this.editPhoneNumber = this.userInfo.phoneNumber || '';
      this.editEmail = this.userInfo.email || '';
      this.editErrors = { userName: '', phoneNumber: '', email: '' };
    },
    
    // 取消整体编辑
    cancelEdit() {
      this.showEditPopup = false;
      this.editUserName = '';
      this.editPhoneNumber = '';
      this.editEmail = '';
      this.editErrors = { userName: '', phoneNumber: '', email: '' };
      this.showPasswordFields = false;
      this.oldPassword = '';
      this.newPassword = '';
      this.confirmPassword = '';
      this.passwordErrors = { oldPassword: '', newPassword: '', confirmPassword: '' };
    },
    
    // 点击遮罩层
    onMaskClick() {
      this.cancelEdit();
    },
    
    // 校验整体编辑表单
    validateAllEdit() {
      let valid = true;
      this.editErrors = { userName: '', phoneNumber: '', email: '' };
      if (!this.editUserName.trim()) {
        this.editErrors.userName = '请输入用户名';
        valid = false;
      } else if (this.editUserName.length < 2 || this.editUserName.length > 16) {
        this.editErrors.userName = '用户名长度必须在2-16位之间';
        valid = false;
      }
      if (!this.editPhoneNumber.trim()) {
        this.editErrors.phoneNumber = '请输入手机号';
        valid = false;
      } else if (!/^1[3-9]\d{9}$/.test(this.editPhoneNumber)) {
        this.editErrors.phoneNumber = '请输入有效的11位手机号码';
        valid = false;
      }
      if (!this.editEmail.trim()) {
        this.editErrors.email = '请输入电子邮箱';
        valid = false;
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.editEmail)) {
        this.editErrors.email = '请输入有效的邮箱地址';
        valid = false;
      }
      return valid;
    },
    
    // 保存整体编辑（含密码）
    saveAllEditWithPassword() {
      // 先校验基本信息
      if (!this.validateAllEdit()) return;
      // 如果展开了密码区，则校验密码
      if (this.showPasswordFields && !this.validatePasswordForm()) return;
      const token = uni.getStorageSync('token');
      uni.showLoading({ title: '保存中...' });
      // 先更新基本信息
      uni.request({
        url: `${API_BASE_URL}/api/user/${this.userInfo.id}`,
        method: 'PUT',
        data: {
          userName: this.editUserName,
          phoneNumber: this.editPhoneNumber,
          email: this.editEmail
        },
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          if (res.statusCode < 200 || res.statusCode >= 300) {
            uni.hideLoading();
            let errorMsg = `更新失败 (${res.statusCode})`;
            if (res.data && res.data.message) {
              errorMsg = res.data.message;
            }
            uni.showToast({ title: errorMsg, icon: 'none' });
            return;
          }
          // 更新本地信息
          this.userInfo.userName = this.editUserName;
          this.userInfo.phoneNumber = this.editPhoneNumber;
          this.userInfo.email = this.editEmail;
          uni.setStorageSync('userInfo', this.userInfo);
          // 如果需要改密码，继续请求
          if (this.showPasswordFields) {
            uni.request({
              url: `${API_BASE_URL}/api/user/${this.userInfo.id}`,
              method: 'PUT',
              data: {
                oldPassword: this.oldPassword,
                newPassword: this.newPassword
              },
              header: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
              },
              success: (res2) => {
                uni.hideLoading();
                if (res2.statusCode < 200 || res2.statusCode >= 300) {
                  let errorMsg = `修改失败 (${res2.statusCode})`;
                  if (res2.data && res2.data.message) {
                    errorMsg = res2.data.message;
                  }
                  if (errorMsg.includes('原密码') || errorMsg.includes('旧密码')) {
                    this.passwordErrors.oldPassword = errorMsg;
                  } else {
                    uni.showToast({ title: errorMsg, icon: 'none' });
                  }
                  return;
                }
                // 密码修改成功
                this.showEditPopup = false;
                this.showPasswordFields = false;
                this.oldPassword = '';
                this.newPassword = '';
                this.confirmPassword = '';
                uni.showModal({
                  title: '密码修改成功',
                  content: '请重新登录',
                  showCancel: false,
                  success: () => {
                    uni.clearStorageSync();
                    uni.reLaunch({ url: '/pages/login/login' });
                  }
                });
              },
              fail: (err2) => {
                uni.hideLoading();
                uni.showToast({ title: '网络错误，请重试', icon: 'none' });
              }
            });
          } else {
            uni.hideLoading();
            this.showEditPopup = false;
            uni.showToast({ title: '更新成功', icon: 'success' });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({ title: '网络错误，请重试', icon: 'none' });
        }
      });
    },
    
    // 验证密码修改表单
    validatePasswordForm() {
      let isValid = true;
      this.passwordErrors = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
      
      // 原密码验证
      if (!this.oldPassword) {
        this.passwordErrors.oldPassword = '请输入原密码';
        isValid = false;
      }
      
      // 新密码验证
      if (!this.newPassword) {
        this.passwordErrors.newPassword = '请输入新密码';
        isValid = false;
      } else if (this.newPassword.length < 6 || this.newPassword.length > 20) {
        this.passwordErrors.newPassword = '密码长度必须在6-20位之间';
        isValid = false;
      } else if (!/(?=.*[A-Za-z])(?=.*\d)/.test(this.newPassword)) {
        this.passwordErrors.newPassword = '密码必须包含字母和数字';
        isValid = false;
      }
      
      // 确认密码验证
      if (!this.confirmPassword) {
        this.passwordErrors.confirmPassword = '请确认新密码';
        isValid = false;
      } else if (this.newPassword !== this.confirmPassword) {
        this.passwordErrors.confirmPassword = '两次输入的密码不一致';
        isValid = false;
      }
      
      return isValid;
    },
    
    // 保存新密码
    savePassword() {
      if (!this.validatePasswordForm()) {
        return;
      }
      const token = uni.getStorageSync('token');
      uni.showLoading({ title: '修改中...' });
      uni.request({
        url: `${API_BASE_URL}/api/user/${this.userInfo.id}`,
        method: 'PUT',
        data: {
          oldPassword: this.oldPassword,
          newPassword: this.newPassword
        },
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          uni.hideLoading();
          
          if (res.statusCode < 200 || res.statusCode >= 300) {
            let errorMsg = `修改失败 (${res.statusCode})`;
            if (res.data && res.data.message) {
              errorMsg = res.data.message;
            }
            
            // 显示密码相关错误
            if (errorMsg.includes('原密码') || errorMsg.includes('旧密码')) {
              this.passwordErrors.oldPassword = errorMsg;
            } else {
              uni.showToast({
                title: errorMsg,
                icon: 'none'
              });
            }
            return;
          }
          
          // 修改成功
          this.showPasswordPopup = false;
          this.oldPassword = '';
          this.newPassword = '';
          this.confirmPassword = '';
          
          // 提示用户重新登录
          uni.showModal({
            title: '密码修改成功',
            content: '请重新登录',
            showCancel: false,
            success: () => {
              // 清除本地存储并跳转到登录页
              uni.clearStorageSync();
              uni.reLaunch({
                url: '/pages/login/login'
              });
            }
          });
        },
        fail: (err) => {
          uni.hideLoading();
          console.error('修改密码请求失败', err);
          uni.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
        }
      });
    },
    
    // 退出登录
    handleLogout() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出当前账号吗？',
        success: (res) => {
          if (res.confirm) {
            // 清除本地存储的token和用户信息
            uni.clearStorageSync();
            
            // 显示退出成功提示
            uni.showToast({
              title: '退出成功',
              icon: 'success'
            });
            
            // 跳转到登录页
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/login/login'
              });
            }, 1000);
          }
        }
      });
    }
  }
}
</script>

<style scoped>
/* 统一使用rpx单位适配小程序 */
.profile-outer {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 40rpx 0 0 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.profile-card {
  background: #fff;
  border-radius: 18rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
  padding: 40rpx 32rpx 32rpx 32rpx;
  width: 92vw;
  max-width: 700rpx;
  margin-bottom: 32rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 32rpx;
}
.avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 80rpx;
  border: 4rpx solid #eee;
  object-fit: cover;
  cursor: pointer;
}
.avatar-hint {
  margin-top: 12rpx;
  font-size: 26rpx;
  color: #aaa;
}
.info-section {
  width: 100%;
  margin-bottom: 24rpx;
}
.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 22rpx 0;
  border-bottom: 1px solid #f0f0f0;
}
.info-item:last-child {
  border-bottom: none;
}
.info-label {
  font-size: 30rpx;
  color: #333;
}
.info-value {
  font-size: 30rpx;
  color: #666;
  text-align: right;
  word-break: break-all;
}
.profile-btns {
  display: flex;
  width: 100%;
  gap: 24rpx;
  margin-top: 24rpx;
}
.edit-all-btn {
  flex: 1;
  height: 80rpx;
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  font-size: 30rpx;
}
.logout-btn {
  flex: 1;
  height: 80rpx;
  background: #fff;
  color: #747bda;
  border: 1px solid #91c9ee;
  border-radius: 10rpx;
  font-size: 30rpx;
}
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
}
.popup-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top-left-radius: 30rpx;
  border-top-right-radius: 30rpx;
  padding: 30rpx 30rpx 20rpx 30rpx;
  z-index: 101;
  max-width: 700rpx;
  margin: 0 auto;
}
.popup-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  text-align: center;
}
.popup-input {
  width: 100%;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1px solid #ddd;
  border-radius: 10rpx;
  font-size: 30rpx;
  margin-bottom: 40rpx;
}
.popup-buttons {
  display: flex;
  gap: 20rpx;
}
.popup-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 10rpx;
  font-size: 30rpx;
}
.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
  border: none;
}
.confirm-btn {
  background-color: #1890ff;
  color: #fff;
  border: none;
}
.error-message {
  color: #ff4d4f;
  font-size: 26rpx;
  margin-top: -30rpx;
  margin-bottom: 20rpx;
  text-align: left;
  min-height: 26rpx;
}
.password-toggle {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #1890ff;
  cursor: pointer;
  margin-bottom: 10rpx;
  user-select: none;
}
.arrow {
  display: inline-block;
  width: 0;
  height: 0;
  margin-left: 8rpx;
  border-left: 10rpx solid transparent;
  border-right: 10rpx solid transparent;
}
.arrow.down {
  border-top: 12rpx solid #1890ff;
}
.arrow.up {
  border-bottom: 12rpx solid #1890ff;
}
</style>